package com.example.server.security.authorize;

import com.example.server.mapper.MenuMapper;
import com.example.common.pojo.Menu;
import com.example.common.pojo.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class JdbcResourceMetaDataProvider implements ResourceMetaDataProvider {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Role> provide(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {


        String requestURI = request.getRequestURI();

        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        List<Role> urlFormRedis = (List<Role>) operations.get("url_" + requestURI);

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        List<Role> allowedRoles = null;

        if (CollectionUtils.isEmpty(Collections.singleton(urlFormRedis))) {
            List<Menu> menus = menuMapper.findAllWithRoles();
            for (Menu menu: menus) {
                if (antPathMatcher.match(menu.getUrl(), requestURI)) {

                    operations.set("url_"+menu.getUrl(),menus);
                    allowedRoles = menu.getRoles();

                }
            }
        }else {
            allowedRoles = urlFormRedis;
        }
        return allowedRoles;
    }

}
